package com.nisovin.magicspells.spells.buff;

import java.util.HashSet;
import java.util.List;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;

import com.nisovin.magicspells.spells.BuffSpell;
import com.nisovin.magicspells.util.MagicConfig;

public class InvulnerabilitySpell extends BuffSpell {

	private HashSet<DamageCause> damageCauses;
	
	private HashSet<String> gods;
	
	public InvulnerabilitySpell(MagicConfig config, String spellName) {
		super(config, spellName);
		
		damageCauses = new HashSet<DamageCause>();
		List<String> causes = getConfigStringList("damage-causes", null);
		if (causes != null) {
			for (String s : causes) {
				s = s.replace(" ","_").replace("-","_").toUpperCase();
				DamageCause cause = DamageCause.valueOf(s);
				if (cause != null) {
					damageCauses.add(cause);
				}
			}
		}
		
		gods = new HashSet<String>();
	}

	@Override
	public boolean castBuff(Player player, float power, String[] args) {
		gods.add(player.getName());
		return true;
	}

	@EventHandler
	public void onEntityDamage(EntityDamageEvent event) {
		if (event.isCancelled()) return;
		if (event.getEntity() instanceof Player && (damageCauses.size() == 0 || damageCauses.contains(event.getCause()))) {
			Player player = (Player)event.getEntity();
			if (gods.contains(player.getName())) {
				if (isExpired(player)) {
					turnOff(player);
				} else {
					event.setCancelled(true);
					if (player.getNoDamageTicks() < player.getMaximumNoDamageTicks() / 2.0F) {
						addUseAndChargeCost(player);
					}
				}
			}
		}
	}
	
	@Override
	public void turnOffBuff(Player player) {
		gods.remove(player.getName());
	}
	
	@Override
	protected void turnOff() {
		gods.clear();
	}

	@Override
	public boolean isActive(Player player) {
		return gods.contains(player.getName());
	}

}
